package com.czh.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.czh.api.CodeApi;
import com.czh.api.UserApi;
import com.czh.domain.TokenDO;
import com.czh.service.TokenService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@Service
public class UserController implements UserApi {

    @Autowired
    private TokenService tokenService;

    @Reference
    private CodeApi codeApi;

    @GetMapping("/info/{token}")
    public String info(@PathVariable String token) {
        TokenDO tokenDO = tokenService.getOne(Wrappers.<TokenDO>lambdaQuery()
                .eq(TokenDO::getToken, token)
                .last("limit 1"));
        if (tokenDO == null) {
            return null;
        }
        return tokenDO.getEmail();
    }

    @GetMapping("/register/{email}/{password}/{code}")
    public int register(@PathVariable String email,
                        @PathVariable String password,
                        @PathVariable String code,
                        HttpServletResponse response) {
        int validate = codeApi.validate(email, code);
        if (validate != 0) {
            return validate;
        }

        TokenDO tokenDO = new TokenDO();
        tokenDO.setEmail(email);
        String token = UUID.randomUUID().toString();
        tokenDO.setToken(token);
        tokenService.save(tokenDO);

        Cookie cookie = new Cookie("token", token);//创建新cookie
        cookie.setMaxAge(5 * 60 * 60);
        cookie.setPath("/");//设置作用域
        response.addCookie(cookie);
        return 0;
    }
}
